package com.xebest.web.controller.homepage;

import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.util.DateUtil;
import com.xebest.util.Money;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.web.controller.order.XeVenOrderController;
import com.xebest.web.form.XeVenHomeCheckForm;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.service.XeVenPurchService;
import com.xebest.web.service.XeVenStoreInventoryService;
import com.xebest.web.view.ErpUserInfo;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 首页相关
 *
 * @author 李书峰
 */
@RestController
@RequestMapping("home")
public class XeVenHomePageController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(XeVenOrderController.class);//日志记录类

    @Autowired
    private XeVenPurchService xeVenPurchService;//采购相关业务操作
    @Autowired
    private XeVenOrderService xeVenOrderService;//订单相关业务操作
    @Autowired
    private XeVenStoreInventoryService xeVenStoreInventoryService;//库存一览相关业务操作

    @RequestMapping("waitCheckOrderNum")
    @ResponseBody
    public BaseResponse queryWaitCheckOrderNum() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal waitCheckOrderNum = xeVenOrderService.queryWaitCheckOrderNum(map);
            waitCheckOrderNum = null != waitCheckOrderNum ? waitCheckOrderNum : new BigDecimal(0);
            map.clear();
            map.put("waitCheckOrderNum", waitCheckOrderNum);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询待审核订单数异常：{}", e);
            return sendAjaxError("查询待审核订单数异常");
        } finally {
            log.info("--------------查询待审核订单数end-------------------");
        }
    }

    @RequestMapping("exceptionOrderNum")
    @ResponseBody
    public BaseResponse queryExceptionOrderNum() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal exceptionOrderNum = xeVenOrderService.queryExceptionOrderNum(map);
            exceptionOrderNum = null != exceptionOrderNum ? exceptionOrderNum : new BigDecimal(0);
            map.clear();
            map.put("exceptionOrderNum", exceptionOrderNum);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询异常订单数异常：{}", e);
            return sendAjaxError("查询异常订单数异常");
        } finally {
            log.info("--------------查询异常订单数end-------------------");
        }
    }

    @RequestMapping("waitSendOrderNum")
    @ResponseBody
    public BaseResponse queryWaitSendOrderNum() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal waitSendOrderNum = xeVenOrderService.queryWaitSendOrderNum(map);
            waitSendOrderNum = null != waitSendOrderNum ? waitSendOrderNum : new BigDecimal(0);
            map.clear();
            map.put("waitSendOrderNum", waitSendOrderNum);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询待发货订单数异常：{}", e);
            return sendAjaxError("查询待发货订单数异常");
        } finally {
            log.info("--------------查询待发货订单数end-------------------");
        }
    }

    @RequestMapping("waitDealPurchOrderNum")
    @ResponseBody
    public BaseResponse queryWaitDealPurchOrderNum() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal waitDealPurchOrderNum = xeVenPurchService.queryWaitDealPurchOrderNum(map);
            waitDealPurchOrderNum = null != waitDealPurchOrderNum ? waitDealPurchOrderNum : new BigDecimal(0);
            map.clear();
            map.put("waitDealPurchOrderNum", waitDealPurchOrderNum);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询待处理采购单数异常：{}", e);
            return sendAjaxError("查询待处理采购单数异常");
        } finally {
            log.info("--------------查询待处理采购单数end-------------------");
        }
    }

    @RequestMapping("stockCost")
    @ResponseBody
    public BaseResponse queryStockCost() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal stockCost = xeVenStoreInventoryService.queryStockCost(map);
            stockCost = null != stockCost ? stockCost : new BigDecimal(0);
            map.clear();
            map.put("stockCost", stockCost);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询库存成本异常：{}", e);
            return sendAjaxError("查询库存成本异常");
        } finally {
            log.info("--------------查询库存成本end-------------------");
        }
    }

    @RequestMapping("monthTotalAmount")
    @ResponseBody
    public BaseResponse queryMonthTotalAmount() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal monthTotalAmount = xeVenOrderService.queryMonthTotalAmount(map);
            monthTotalAmount = null != monthTotalAmount ? monthTotalAmount : new BigDecimal(0);
            map.clear();
            map.put("monthTotalAmount", monthTotalAmount);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询本月销售总额异常：{}", e);
            return sendAjaxError("查询本月销售总额异常");
        } finally {
            log.info("--------------查询本月销售总额end-------------------");
        }
    }

    @RequestMapping("monthTradeUserNum")
    @ResponseBody
    public BaseResponse queryMonthTradeUserNum() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal monthTradeUserNum = xeVenOrderService.queryMonthTradeUserNum(map);
            monthTradeUserNum = null != monthTradeUserNum ? monthTradeUserNum : new BigDecimal(0);
            map.clear();
            map.put("monthTradeUserNum", monthTradeUserNum);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询本月交易用户数异常：{}", e);
            return sendAjaxError("查询本月交易用户数异常");
        } finally {
            log.info("--------------查询本月交易用户数end-------------------");
        }
    }

    @RequestMapping("monthPurchAmount")
    @ResponseBody
    public BaseResponse queryMonthPurchAmount() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal monthPurchAmount = xeVenPurchService.queryMonthPurchAmount(map);
            monthPurchAmount = null != monthPurchAmount ? monthPurchAmount : new BigDecimal(0);
            map.clear();
            map.put("monthPurchAmount", monthPurchAmount);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询本月采购总额异常：{}", e);
            return sendAjaxError("查询本月采购总额异常");
        } finally {
            log.info("--------------查询本月采购总额end-------------------");
        }
    }

    @RequestMapping("homeView")
    @ResponseBody
    public BaseResponse homeView() {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userCode", userInfo.getUserCode());
            // 3、输出结果
            BigDecimal waitCheckOrderNum = xeVenOrderService.queryWaitCheckOrderNum(map);
            BigDecimal exceptionOrderNum = xeVenOrderService.queryExceptionOrderNum(map);
            BigDecimal waitSendOrderNum = xeVenOrderService.queryWaitSendOrderNum(map);
            BigDecimal waitDealPurchOrderNum = xeVenPurchService.queryWaitDealPurchOrderNum(map);
            BigDecimal stockCost = xeVenStoreInventoryService.queryStockCost(map);
            BigDecimal monthTotalAmount = xeVenOrderService.queryMonthTotalAmount(map);
            BigDecimal monthTradeUserNum = xeVenOrderService.queryMonthTradeUserNum(map);
            BigDecimal monthPurchAmount = xeVenPurchService.queryMonthPurchAmount(map);

            waitCheckOrderNum = null != waitCheckOrderNum ? waitCheckOrderNum : new BigDecimal(0);
            exceptionOrderNum = null != exceptionOrderNum ? exceptionOrderNum : new BigDecimal(0);
            waitSendOrderNum = null != waitSendOrderNum ? waitSendOrderNum : new BigDecimal(0);
            waitDealPurchOrderNum = null != waitDealPurchOrderNum ? waitDealPurchOrderNum : new BigDecimal(0);
            stockCost = null != stockCost ? stockCost : new BigDecimal(0);
            monthTotalAmount = null != monthTotalAmount ? monthTotalAmount : new BigDecimal(0);
            monthTradeUserNum = null != monthTradeUserNum ? monthTradeUserNum : new BigDecimal(0);
            monthPurchAmount = null != monthPurchAmount ? monthPurchAmount : new BigDecimal(0);

            map.clear();

            map.put("waitCheckOrderNum", waitCheckOrderNum);
            map.put("exceptionOrderNum", exceptionOrderNum);
            map.put("waitSendOrderNum", waitSendOrderNum);
            map.put("waitDealPurchOrderNum", waitDealPurchOrderNum);
            map.put("stockCost", stockCost);
            map.put("monthTotalAmount", monthTotalAmount);
            map.put("monthTradeUserNum", monthTradeUserNum);
            map.put("monthPurchAmount", monthPurchAmount);

            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("查询首页数据异常：{}", e);
            return sendAjaxError("查询首页数据异常");
        } finally {
            log.info("--------------查询首页数据end-------------------");
        }
    }


    /**
     * 查询每日销售额（销售额/订单数）
     *
     * @author chenjing
     */
    @RequestMapping("getAmountByMonth")
    @ResponseBody
    public BaseResponse getAmountByMonth(@RequestBody XeVenHomeCheckForm checkForm) {
        if (null == checkForm || null == checkForm.getMonth() || StringUtils.isBlank(checkForm.getMonth())) {
            return sendAjaxError();
        }
        String month = checkForm.getMonth();
        String year = checkForm.getYear();
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userCode", userInfo.getUserCode());
        map.put("paramType", 2);
        //map.put("userCode", "SH1709221914147");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String date = sdf.format(new Date());
        if (null == month || StringUtils.isBlank(month)) {
            month = date.substring(5, 7);
        }
        if (null == year || StringUtils.isBlank(year)) {
            year = date.substring(0, 4);
        }
        //int year = Integer.parseInt(date.substring(0,4));
        int monthDays = DateUtil.getMonthLastDay(Integer.parseInt(year), Integer.parseInt(month));
        map.put("month", year + "-" + month);
        map.put("paramValue", year + "-" + month);
        List<Map<String, Object>> ordersAmount = xeVenOrderService.queryOrderCountAmountByParams(map);
        //每日销售额
        List<String> payAmount = new ArrayList<>();
        // 订单数（每日）
        List<String> orderNum = new ArrayList<>();
        // x轴  日期
        List<String> dateList = new ArrayList<>();
        // 货到付款（每日）
        List<String> cod = new ArrayList<>();
        //  [ 在线支付（每日）
        List<String> payOnline = new ArrayList<>();
        //  交易用户（每日）
        List<String> userNum = new ArrayList<>();
        List<Map<String, Object>> ordersAmountList = new ArrayList<>();
        if (Integer.parseInt(month) <= 9) {
            month = "0" + month;
        }
        for (int i = 1; i <= monthDays; i++) {
            Map ordersAmountMap = new HashedMap();
            String formatDate = "";
            if (i <= 9) {
                formatDate = year + "-" + month + "-" + "0" + i;
            } else {
                formatDate = year + "-" + month + "-" + i;
            }

            String orderNumsByDay = "0";
            String totalAmount = "0";
            String codByDay = "0";
            String payOnlineByDay = "0";
            String userNumByDay = "0";
            //ordersAmountMap.put("createDate",formatDate);
            //ordersAmountMap.put("totalAmount",0);
            //ordersAmountMap.put("orderNum",0);
            for (Map orderMap : ordersAmount) {
                if (orderMap.containsKey("createDate") && orderMap.get("createDate").toString().trim().equals(formatDate)) {
                    orderNumsByDay = orderMap.get("orderNum").toString();
                    totalAmount = Money.of(orderMap.get("totalAmount").toString()).divide(10000).toMoneyString();
                    codByDay = Money.of(orderMap.get("cod").toString()).divide(10000).toMoneyString();
                    payOnlineByDay = Money.of(orderMap.get("payOnline").toString()).divide(10000).toMoneyString();
                    userNumByDay = orderMap.get("userNum").toString();
                    //ordersAmountMap.put("totalAmount",orderMap.get("totalAmount"));
                    //ordersAmountMap.put("orderNum",orderMap.get("orderNum"));
                    break;
                }
            }
            dateList.add(formatDate);
            payAmount.add(totalAmount);
            cod.add(codByDay);
            payOnline.add(payOnlineByDay);
            orderNum.add(orderNumsByDay);
            userNum.add(userNumByDay);
            ordersAmountList.add(ordersAmountMap);
        }
        Map responseMap = new HashedMap();
        Map sourceMap = new HashedMap();
        sourceMap.put("payAmount", payAmount);
        sourceMap.put("orderNum", orderNum);
        sourceMap.put("dateList", dateList);
        sourceMap.put("cod", cod);
        sourceMap.put("payOnline", payOnline);
        sourceMap.put("userNum", userNum);
        responseMap.put("salesAmountByDays", sourceMap);

        //右侧饼图
        BigDecimal orderNums = xeVenOrderService.queryOrderCountByParams(map);
        //当月销售总额
        BigDecimal monthTotalAmount = xeVenOrderService.queryMonthTotalAmountByParams(map);
        //当月销售总额
        BigDecimal monthTradeUserNum = xeVenOrderService.queryMonthTradeUserNumByParams(map);

        //统计交易中商品分类信息
        List<Map<String, Object>> proOrgList = xeVenOrderService.queryProOrgCountByParams(map);
        List<Map<String, Object>> proOrgViewList = new ArrayList<>();
        for (Map orderMap : proOrgList) {
            Map viewMap = new HashedMap();
            if (null != orderMap && orderMap.containsKey("orgCode") && StringUtils.isNotBlank(orderMap.get("orgCode").toString())) {
                String orgCode = orderMap.get("orgCode").toString();
                orgCode = orgCode.substring(1, orgCode.length());
                String cateName = XeBaseUtil.baseUtil.getCategoryName(orgCode);
                viewMap.put("name", cateName);
                viewMap.put("value", Money.of(orderMap.get("totalAmount").toString()).divide(10000).toMoneyString());
                proOrgViewList.add(viewMap);
            }
        }
        Map resultMap = new HashedMap();
        //月订单数
        resultMap.put("orderNum", orderNums);
        //月销售额
        resultMap.put("salesAmount", Money.of(monthTotalAmount).divide(10000).toMoneyString());
        //月交易用户
        resultMap.put("userNum", monthTradeUserNum);
        //本月商品分类饼图统计
        //resultMap.put("proOrgList",proOrgList);
        responseMap.put("salesAmount", resultMap);
        responseMap.put("salesAmountByMonth", proOrgViewList);
        return sendAjaxOK(responseMap);
    }

    /**
     * 获取每月销售额总计
     *
     * @author chenjing
     */
    @RequestMapping("getTotalAmountByMonth")
    @ResponseBody
    public BaseResponse getTotalAmountByMonth(@RequestBody String month) {
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userCode", userInfo.getUserCode());
        //map.put("userCode", "SH1709221914147");
        map.put("paramType", 2);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        String paramValue = df.format(new Date());
        if (null != month && StringUtils.isNotBlank(month)) {
            int year = Integer.parseInt(paramValue.substring(0, 4));
            paramValue = year + "-" + month;
        }
        map.put("paramValue", paramValue);
        BigDecimal orderNum = xeVenOrderService.queryOrderCountByParams(map);
        //当月销售总额
        BigDecimal monthTotalAmount = xeVenOrderService.queryMonthTotalAmountByParams(map);
        //当月交易客户数
        BigDecimal monthTradeUserNum = xeVenOrderService.queryMonthTradeUserNumByParams(map);

        //统计交易中商品分类信息
        List<Map<String, Object>> proOrgList = xeVenOrderService.queryProOrgCountByParams(map);
        for (Map orderMap : proOrgList) {
            if (null != orderMap && orderMap.containsKey("orgCode") && StringUtils.isNotBlank(orderMap.get("orgCode").toString())) {
                String orgCode = orderMap.get("orgCode").toString();
                orgCode = orgCode.substring(1, orgCode.length());
                String cateName = XeBaseUtil.baseUtil.getCategoryName(orgCode);
                orderMap.put("cateName", cateName);
            }
        }
        Map resultMap = new HashedMap();
        //月订单数
        resultMap.put("orderNum", orderNum);
        //月销售额
        resultMap.put("monthTotalAmount", monthTotalAmount);
        //月交易用户
        resultMap.put("monthTradeUserNum", monthTradeUserNum);
        //本月商品分类饼图统计
        resultMap.put("proOrgList", proOrgList);
        return sendAjaxOK(resultMap);
    }
}
  
